﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ImgRemakeCore
{
    public class Resize
    {
        /// <summary> 
        /// 生成缩略图:背景颜色可以设置
        /// </summary> 
        /// <param name="originalImagePath">源图路径（物理路径）</param> 
        /// <param name="thumbnailPath">缩略图路径（物理路径）</param> 
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="byColor">空白背景填充颜色</param>
        public static void MakeThumbnail2(string originalImagePath, string thumbnailPath, int width, int height, string byColor)
        {
            //获取原始图片  
            Image originalImage = Image.FromFile(originalImagePath);
            //缩略图画布宽高  
            int towidth = width;
            int toheight = height;
            //原始图片写入画布坐标和宽高(用来设置裁减溢出部分)  
            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;
            //原始图片画布,设置写入缩略图画布坐标和宽高(用来原始图片整体宽高缩放)  
            int bg_x = 0;
            int bg_y = 0;
            int bg_w = towidth;
            int bg_h = toheight;
            //倍数变量  
            double multiple = 0;
            //获取宽长的或是高长与缩略图的倍数  
            if (originalImage.Width >= originalImage.Height)
            {
                multiple = (double)originalImage.Width / (double)width;
            }
            else
            {
                multiple = (double)originalImage.Height / (double)height;
            }
            //上传的图片的宽和高小等于缩略图  
            if (ow <= width && oh <= height)
            {
                //缩略图按原始宽高  
                bg_w = originalImage.Width;
                bg_h = originalImage.Height;
                //空白部分用背景色填充  
                bg_x = Convert.ToInt32(((double)towidth - (double)ow) / 2);
                bg_y = Convert.ToInt32(((double)toheight - (double)oh) / 2);
            }
            //上传的图片的宽和高大于缩略图  
            else
            {
                //宽高按比例缩放  
                bg_w = Convert.ToInt32((double)originalImage.Width / multiple);
                bg_h = Convert.ToInt32((double)originalImage.Height / multiple);
                //空白部分用背景色填充  
                bg_y = Convert.ToInt32(((double)height - (double)bg_h) / 2);
                bg_x = Convert.ToInt32(((double)width - (double)bg_w) / 2);
            }
            //新建一个bmp图片,并设置缩略图大小.  
            Image bitmap = new Bitmap(towidth, toheight);
            //新建一个画板  
            Graphics g = Graphics.FromImage(bitmap);
            //设置高质量插值法  
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
            //设置高质量,低速度呈现平滑程度  
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空画布并设置背景色  
            g.Clear(ColorTranslator.FromHtml(byColor));
            //在指定位置并且按指定大小绘制原图片的指定部分  
            //第一个System.Drawing.Rectangle是原图片的画布坐标和宽高,第二个是原图片写在画布上的坐标和宽高,最后一个参数是指定数值单位为像素  
            g.DrawImage(originalImage, new Rectangle(bg_x, bg_y, bg_w, bg_h), new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel);
            try
            {
                //获取图片类型  
                string fileExtension = Path.GetExtension(originalImagePath).ToLower();
                //按原图片类型保存缩略图片,不按原格式图片会出现模糊,锯齿等问题.  
                switch (fileExtension)
                {
                    case ".gif": bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Gif); break;
                    case ".jpg": bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg); break;
                    case ".bmp": bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Bmp); break;
                    case ".png": bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Png); break;
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }


        ///// <summary> 
        ///// 生成缩略图：无填充背景
        ///// </summary> 
        ///// <param name="originalImagePath">源图路径（物理路径）</param> 
        ///// <param name="thumbnailPath">缩略图路径（物理路径）</param> 
        ///// <param name="width">缩略图宽度</param> 
        ///// <param name="height">缩略图高度</param>    
        //    public static void MakeThumbnail2(string originalImagePath, string thumbnailPath, int width, int height)
        //    {
        //        //获取原始图片
        //        Image originalImage = Image.FromFile(originalImagePath);
        //        //缩略图画布宽高
        //        int towidth = width;//缩略图宽度
        //        int toheight = height;//缩略图高度
        //                              //原始图片写入画布坐标和宽高(用来设置裁减溢出部分)
        //        int x = 0;
        //        int y = 0;
        //        int ow = originalImage.Width;//原图宽度
        //        int oh = originalImage.Height;//原图高度

        //        //先判断宽，宽大于指定宽度的话将宽设置为指定宽度，高度等比例缩放。
        //        if (originalImage.Width > width)
        //        {
        //            towidth = width;
        //            toheight = originalImage.Height * towidth / originalImage.Width;
        //        }
        //        else
        //        {
        //            towidth = originalImage.Width;
        //            toheight = originalImage.Height;
        //        }
        //        //再判断高，高大于指定高度的话将高设置为指定高度，宽度等比例缩放。
        //        if (toheight > height)
        //        {
        //            toheight = height;
        //            towidth = originalImage.Width * toheight / originalImage.Height;
        //        }

        //        //新建一个bmp图片 
        //        Image bitmap = new Bitmap(towidth, toheight);

        //        //新建一个画板 
        //        Graphics g = Graphics.FromImage(bitmap);

        //        //设置高质量插值法 
        //        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

        //        //设置高质量,低速度呈现平滑程度 
        //        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

        //        //清空画布并以透明背景色填充 
        //        g.Clear(Color.Transparent);

        //        //在指定位置并且按指定大小绘制原图片的指定部分
        //        g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight), new Rectangle(x, y, ow, oh),
        //GraphicsUnit.Pixel);

        //        try
        //        {
        //            //获取图片类型
        //            string fileExtension = Path.GetExtension(originalImagePath).ToLower();
        //            //按原图片类型保存缩略图片,不按原格式图片会出现模糊,锯齿等问题.
        //            switch (fileExtension)
        //            {
        //                case ".gif": bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Gif); break;
        //                case ".jpg": bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg); break;
        //                case ".bmp": bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Bmp); break;
        //                case ".png": bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Png); break;
        //            }
        //        }
        //        catch (Exception e)
        //        {
        //            throw e;
        //        }
        //        finally
        //        {
        //            originalImage.Dispose();
        //            bitmap.Dispose();
        //            g.Dispose();
        //        }
        //    }

        /// <summary>
        /// 等比缩放图片
        /// </summary>
        /// <param name="pathImageFrom">图片地址（服务器绝对路径）</param>
        /// <param name="maxSize">宽和高最大值</param>
        public static void ChangePicSize(string pathImageFrom, int maxSize, string pathSave)
        {
            Image imageFrom = null;
            if (File.Exists(pathImageFrom))
            {
                imageFrom = Image.FromFile(pathImageFrom);
                // 源图宽度及高度   
                int imageFromWidth = imageFrom.Width;
                int imageFromHeight = imageFrom.Height;
                // 生成的缩略图实际宽度及高度  
                int bitmapWidth = imageFromWidth;
                int bitmapHeight = imageFromHeight;
                if (imageFromWidth > maxSize || imageFromHeight > maxSize)
                {
                    if (imageFromWidth > imageFromHeight)
                    {
                        bitmapWidth = maxSize;
                        bitmapHeight = imageFromHeight * maxSize / imageFromWidth;
                    }
                    else
                    {
                        bitmapWidth = imageFromWidth * maxSize / imageFromHeight;
                        bitmapHeight = maxSize;
                    }
                }

                // 创建画布   
                Bitmap bmp = new Bitmap(bitmapWidth, bitmapHeight);
                Graphics g = Graphics.FromImage(bmp);
                // 用透明填充清空   
                g.Clear(Color.Transparent);
                // 指定高质量的双三次插值法。执行预筛选以确保高质量的收缩。此模式可产生质量最高的转换图像。
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                // 指定高质量、低速度呈现。   
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                // 在指定位置并且按指定大小绘制指定的 Image 的指定部分。   
                g.DrawImage(imageFrom, new Rectangle(0, 0, bitmapWidth, bitmapHeight), new Rectangle(0, 0, imageFromWidth, imageFromHeight), GraphicsUnit.Pixel);

                imageFrom.Dispose();
                Stream ms = new MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                bmp.Save(pathSave, System.Drawing.Imaging.ImageFormat.Jpeg);

                Console.WriteLine("质量&像素压缩生成目标文件:" + pathSave);
                Console.WriteLine($"目标文件:Width:{bmp.Width},Height:{bmp.Height},Size:{Math.Ceiling(ms.Length / 1024.0)}KB");
                bmp.Dispose();
                g.Dispose();
            }
        }



        //// <summary> 
        /// 生成缩略图 
        /// </summary> 
        /// <param name="originalImagePath">源图路径（物理路径）</param> 
        /// <param name="thumbnailPath">缩略图路径（物理路径）</param> 
        /// <param name="width">缩略图宽度</param> 
        /// <param name="height">缩略图高度</param> 
        /// <param name="mode">生成缩略图的方式(HW,W,H,CUT)</param>     
        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
        {
            Image originalImage = Image.FromFile(originalImagePath);

            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            if (originalImage.Width <= width && originalImage.Height <= height)
            {
                File.Copy(originalImagePath, thumbnailPath, true);
                originalImage.Dispose();
                return;
            }
            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形）                 
                    break;
                case "W"://指定宽，高按比例                     
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H"://指定高，宽按比例 
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "CUT"://指定高宽裁减（不变形）        
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }

            Stream ms = new MemoryStream();
            //新建一个bmp图片 
            Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
            //新建一个画板 
            Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            //设置高质量插值法 
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度 
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空画布并以透明背景色填充 
            g.Clear(Color.Transparent);
            //在指定位置并且按指定大小绘制原图片的指定部分 
            g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight), new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel);
            try
            {
                //以jpg格式保存缩略图 
                bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                if (mode == "CUT")
                {
                    Console.WriteLine("生成预览文件:" + thumbnailPath);
                }
                else
                {
                    Console.WriteLine("质量&像素压缩生成目标文件:" + thumbnailPath);
                }
                Console.WriteLine($"目标文件信息:Width:{bitmap.Width},Height:{bitmap.Height},Size:{Math.Ceiling(ms.Length / 1024.0)}KB");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
            finally
            {
                ms.Close();
                ms.Dispose();
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }

    }
}
